<template>
  <div style="padding: 10px 40px">
    <el-row>
      <el-col :span="20">
        <el-page-header
          style="margin: 20px 0"
          @back="goBack"
          :content="paper.name"
        >
        </el-page-header>
      </el-col>
      <el-col :span="4">
        <Inteval :initialMinutes="paper.limitTime" />
      </el-col>
    </el-row>
    <div style="margin: 20px 0">
      <el-row>
        <el-col :span="16" style="padding-right: 20px; box-sizing: border-box">
          <div v-if="paperPracticeList.length > 0">
            <div
              v-for="(practice, index) in paperPracticeList"
              :key="index"
              style="padding: 15px 0; border-bottom: 1px solid #f1f1f1"
            >
              <div>
                <span
                  style="margin-right: 10px; font-size: 12px; color: #606266"
                  >第{{ index + 1 }}题</span
                >
                <span class="practice-type" v-if="practice.practiceType === '1'"
                  >单选题</span
                >
                <span
                  class="practice-type"
                  v-else-if="practice.practiceType === '2'"
                  >多选题</span
                >
                <span
                  class="practice-type"
                  v-else-if="practice.practiceType === '3'"
                  >填空题</span
                >
                <span class="practice-type" v-else>判断题</span>
              </div>
              <div v-html="practice.askItem"></div>
              <div>
                <div v-if="practice.practiceType === '1'">
                  <el-radio-group
                    v-model="practice.oneSelectedAnswer"
                    @change="handleSelectChange"
                  >
                    <el-radio
                      style="width: 100%; margin: 10px 0"
                      v-for="(option, index) in practice.entityQuestion"
                      :key="index"
                      :label="option.type"
                    >
                      {{ option.type }}&nbsp;.&nbsp;{{ option.value }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else-if="practice.practiceType === '2'">
                  <div
                    v-for="(option, n) in practice.entityQuestion"
                    :key="n"
                    style="margin: 15px 0; font-size: 14px; color: #606266"
                  >
                    <span
                      :style="{
                        border: haveOptionExit(option)
                          ? '4px solid rgb(57, 148, 238)'
                          : '1px solid #98999a'
                      }"
                      class="selected"
                      @click="optionClick(option)"
                    ></span>
                    <span
                      :style="{
                        color: haveOptionExit(option)
                          ? 'rgb(57, 148, 238)'
                          : '#606266'
                      }"
                    >
                      <span style="margin-right: 6px">{{ option.type }}.</span>
                      <span>{{ option.value }}</span>
                    </span>
                  </div>
                </div>
                <div v-else-if="practice.practiceType === '3'">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="输入答案"
                    v-model="practice.postAnswer"
                  >
                  </el-input>
                </div>
                <div v-else>
                  <el-radio-group v-model="practice.judgeAnswer">
                    <el-radio
                      style="width: 100%; margin: 10px 0"
                      v-for="(option, index) in practice.entityQuestion"
                      :key="index"
                      :label="option.type"
                    >
                      {{ option.type }}&nbsp;.&nbsp;{{ option.value }}
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty description="卷子暂时未收录题目"></el-empty>
          </div>
        </el-col>
        <el-col :span="8">
          <Evaluations :contentId="paper.id" contentType="试卷模块" />
        </el-col>
      </el-row>
    </div>
    <div v-if="paperPracticeList.length > 0">
      <el-button @click="postPaper" size="mini" round>立即提交</el-button>
    </div>
  </div>
</template>

<script>
import Inteval from "@/components/Inteval";
import Evaluations from "@/components/Evaluations";

export default {
  components: { Inteval, Evaluations },
  data() {
    return {
      paper: {},
      paperPracticeList: [],
      oneSelectedAnswer: "",
      answer: {},
      optionSelcted: [],
      startTime: null
    };
  },
  created() {
    this.getPaperId();
    // 获取时间戳
    this.startTime = new Date().getTime();
  },
  methods: {
    haveOptionExit(option) {
      const entity = this.optionSelcted.find(
        entity => entity.type === option.type
      );
      return entity === undefined ? false : true;
    },
    optionClick(option) {
      // 两步骤： 已经选中，取消；未选中，就是选中；未找到：undefined；找到了返回对象
      const optionEntity = this.optionSelcted.find(
        entity => entity.type === option.type
      );
      option.isSelected = !option.isSelected;
      if (optionEntity === undefined) {
        this.optionSelcted.push(option);
      } else {
        this.optionSelcted = this.optionSelcted.filter(
          entity => entity.type !== option.type
        );
      }
    },
    // 提交试卷
    postPaper() {
      let testHistories = [];
      // 过滤及封装对象
      console.log(this.paperPracticeList);
      for (const practice of this.paperPracticeList) {
        const testHistory = {
          practiceId: practice.practiceId,
          paperId: practice.paperId,
          answer: this.getAnswer(practice),
          startTime: this.startTime,
          endTime: new Date().getTime()
        };
        testHistories.push(testHistory);
      }
      this.$axios.post(`/test-history/save`, testHistories).then(response => {
        const { data } = response;
        if (data.code === 200) {
          this.$swal.fire({
            title: "交卷成功",
            text: response.data.msg,
            icon: "success",
            showConfirmButton: false,
            timer: 1000
          });
          this.$router.go(-1);
        }
      });
    },
    // 过滤答案
    getAnswer(practice) {
      // 单选题答案
      if (practice.practiceType === "1") {
        return JSON.stringify(practice.oneSelectedAnswer.split(","));
      } else if (practice.practiceType === "4") {
        // 判断题答案
        return JSON.stringify(practice.judgeAnswer.split(","));
      } else if (practice.practiceType === "3") {
        // 填空题答案
        return JSON.stringify(practice.postAnswer);
      } else {
        // 多选题
        const questionList = practice.entityQuestion.filter(
          question => question.isSelected
        );
        if (!questionList.length) {
          return "";
        }
        const list = questionList.map(entity => entity.type);
        return JSON.stringify(list);
      }
    },
    changePracticeType(practice) {
      if (practice.practiceType === "1") {
        return "单选题";
      } else if (practice.practiceType === "2") {
        return "多选题";
      } else if (practice.practiceType === "3") {
        return "填空题";
      } else {
        return "判断题";
      }
    },
    parseQuestion(practice) {
      return JSON.parse(practice.question);
    },
    goBack() {
      this.$router.go(-1);
    },
    getPaperId() {
      const paperJson = sessionStorage.getItem("paperInfo");
      this.paper = JSON.parse(paperJson);
      this.loadPracticeList(this.paper.id);
    },
    loadPracticeList(paperId) {
      const paperPracticeQueryDto = { paperId: paperId };
      this.$axios
        .post("/paper-practice/queryWithHistoryAnswer", paperPracticeQueryDto)
        .then(response => {
          const { data } = response;
          if (data.code === 200) {
            this.paperPracticeList = data.data.practices; // 返回的试题列表
            const lastAnswerData = data.data.testHistoryDtos; // 后端返回的作答记录数组

            for (const practice of this.paperPracticeList) {
              // 解析问题内容
              practice.entityQuestion = JSON.parse(practice.question);
              practice.entityQuestion.forEach(
                option => (option.isSelected = false)
              );
              // 默认所有选项未选中
            }

            // 选择第一个和试题列表对应的作答记录
            const lastAnswerList = this.paperPracticeList.map(elem => {
              let temp = null;
              for (const answer of lastAnswerData) {
                if (answer.practiceId === elem.practiceId) {
                  temp = answer;
                  break;
                }
              }
              return temp;
            });
            this.recallAnswer(this.paperPracticeList, lastAnswerList);
          }
        });
    },

    recallAnswer(practiceList, savedAnswerList) {
      console.log(practiceList, savedAnswerList);
      for (let i = 0; i < savedAnswerList.length; i++) {
        const answer = savedAnswerList[i];
        if (answer !== null) {
          // 找到对应的试题
          // const practice = practiceList[i];
          // 填空题
          if (practiceList[i].practiceType === "3") {
            // console.log(3);
            this.$set(practiceList[i], "postAnswer", answer.answer);
            // practiceList[i].postAnswer = answer.answer;
          } else if (practiceList[i].practiceType === "4") {
            // console.log(4);
            let temp = JSON.parse(answer.answer);
            // console.log(temp);
            // 判断题
            this.$set(practiceList[i], "judgeAnswer", temp[0]);
            // practiceList[i].judgeAnswer = temp[0];
          } else if (
            practiceList[i].practiceType === "1" ||
            practiceList[i].practiceType === "2"
          ) {
            // console.log(1);
            // 单选题、多选题
            const answerList = JSON.parse(answer.answer);
            // console.log(answerList, practiceList[0]);
            for (const answerType of answerList) {
              if (practiceList[i].practiceType === "1") {
                // console.log(answerType)
                this.$set(practiceList[i], "oneSelectedAnswer", answerType);
                // this.oneSelectedAnswer = answerType;
              }
              practiceList[i].entityQuestion.forEach(
                option => (option.isSelected = option.type === answerType)
              );
            }
          } else {
            console.log(practiceList[i]);
          }
        }
      }
    },

    handleSelectChange(e) {
      console.log(e);
    }
  }
};
</script>

<style scoped lang="scss">
.selected {
  display: inline-block;
  margin-right: 15px;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
  border-radius: 6px;
  border: 1px solid #98999a;
  cursor: pointer;
}

.selected:hover {
  border: 1px solid rgb(57, 148, 238);
}

.practice-type {
  margin-right: 10px;
  display: inline-block;
  padding: 3px 5px;
  border-radius: 3px;
  background-color: rgb(235, 237, 245);
  color: rgb(43, 121, 203);
  font-size: 12px;
}
</style>
